import {StyleSheet, View, Text, ScrollView, FlatList, TouchableOpacity, Alert, Image} from 'react-native';
import { useSafeAreaInsets } from "react-native-safe-area-context"
// import NewRenderComponent from "@/components/NewRendItem/index"
import React, {useCallback, useEffect, useRef, useState} from "react";
import 'react-native-get-random-values';
import OpenIMSDKRN, { OpenIMEmitter } from 'open-im-sdk-rn';
import {v4 as uuidv4} from "uuid";
import  { useConversationStore } from "@/hooks/im/conversation"
import {useGlobalEvent} from "@/hooks/im/useGlobalEvent";
import {router} from "expo-router";
import { GestureHandlerRootView, Swipeable } from 'react-native-gesture-handler';
import {MessageItem} from "open-im-sdk-rn/lib/typescript/types/entity";
import {formatConversionTime, getConversationContent, initSDK} from "@/utils/ImCommon";
import avator from "@/assets/images/me/avator.png";
import { scaleSize } from "@/utils/screenSize"
import {showToast} from "@/utils/rootToast";
import {useDispatch, useSelector} from "react-redux";
import {AppDispatch, RootState} from "@/store";
import {getIMToken, getToken} from "@/utils/index"
import {useFocusEffect} from "@react-navigation/native";
import GroupAvatar from "@/components/GroupAvatar/index"
import {getGrainInfoDetail, getUserInfoDetail} from "@/store/slices/loginSlice";
import {getOpenImAdminByToken, getOpenImSelfByToken} from '@/services/openImServices'
import { getImTokenAdmin } from "@/services/login"
import { platformID} from "@/utils/ImCommon"
import Empty from "@/components/empty";


const data = [
    { id: '1', name: 'Alice', avatar: 'https://example.com/avatar1.jpg' },
    { id: '2', name: 'Bob', avatar: 'https://example.com/avatar2.jpg' },
    { id: '3', name: 'Charlie', avatar: 'https://example.com/avatar3.jpg' },
];

export default function newScreen() {
    const insets = useSafeAreaInsets();
    useGlobalEvent();

    const conversationList = useConversationStore((state) => state.conversationList);
    const updateCurrentConversation = useConversationStore((state) => state.updateCurrentConversation);
    const setConversationListL = useConversationStore((state) => state.setConversationListL);
    const unReadCount = useConversationStore((state) => state.unReadCount);

    const [openItemId, setOpenItemId] = useState(null); // 记录当前打开的项的 ID
    const [imToken, setImToken] = useState("");
    const swipeableRefs = useRef([]); // 用于保存 Swipeable 组件的引用
    const [isLogin, setIsLogin] = useState(false);

    const login = useSelector((state: RootState) => state.login);

    const dispatch = useDispatch<AppDispatch>();

    const getIMTokenByStorage = async function () {
        const token = await getIMToken();
        if (token) {
            setImToken(token);
        };
    };

    useEffect( () => {
        dispatch(getUserInfoDetail());
        dispatch(getGrainInfoDetail());

    }, [])

    const checkHasTokenStatus = async () => {
        const token = await getToken();
        console.log('token', token);
        if (token) {
            setIsLogin(true);
        };
    };


    useFocusEffect(
        useCallback(() => {
            checkHasTokenStatus();
            if (isLogin) {
                getIMTokenByStorage();
            };
            return () => console.log("Tab unfocused");
        }, [])
    );

    useEffect(() => {

        // getOpenImAdminByToken()
        //     .then(res => {
        //
        //     })
        //     .catch(err => {
        //         console.log('err', err);
        //     })

        // getImTokenAdmin()
        //     .then(res => {
        //         const adminToken = res?.data?.imAdminToken;
        //         getOpenImSelfByToken(adminToken, login?.userInfo?.uid, platformID)
        //             .then(r => {
        //                 console.log('r', r.data.token);
        //                 initSDK(login?.userInfo?.uid, r.data.token);
        //             })
        //             .catch(e => {
        //                 console.log('e', e);
        //             });
        //         console.log('getImTokenAdmingetImTokenAdmingetImTokenAdmin', res);
        //     })
        //     .catch(err => {
        //         console.log('err', err);
        //     })


        // const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiJpbUFkbWluIiwiUGxhdGZvcm1JRCI6MTAsImV4cCI6MTc0NzgxMjkzNCwiaWF0IjoxNzQwMDM2OTI5fQ.WddJPmFPDXkGjl_fgBp3rveIToNFveIEW-6JHyhtRRU';



        //
        // console.log('login?.locationInfo?.uid', login?.userInfo?.uid);
        // console.log('imTokenimToken', imToken);
        //
        // console.log('login', login);
        // console.log("uuidv4uuidv4uuidv4", uuidv4());
    }, [])



    const newRenderComponent = function ({ item }) {
        // console.log('newRenderComponent', item);

        const formattedMessage = () => {
            let parsedMessage: MessageItem | undefined;
            try {
                parsedMessage = JSON.parse(item.latestMsg);
            } catch (e) {
                console.log("parsedMessage error");
            }
            if (!parsedMessage) return "";
            return getConversationContent(parsedMessage, login?.userInfo?.uid);
        };



        const renderRightActions = (id) => (
            <TouchableOpacity style={styles.deleteButton} onPress={() => handleDelete(id)}>
                <Text style={styles.deleteText}>删除</Text>
            </TouchableOpacity>
        );

        const handleDelete = (id) => {
            Alert.alert(
                '删除确认',
                '您确定要删除这条消息吗？',
                [
                    {
                        text: '取消',
                        style: 'cancel',
                    },
                    {
                        text: '确定',
                        onPress: () => {
                            OpenIMSDKRN.deleteConversationAndDeleteAllMsg(id, uuidv4());
                            console.log('id', id);
                            const list = [];
                            conversationList.forEach((item: any) => {
                                if (item.conversationID !== id) {
                                    list.push(item);
                                };
                            });
                            setConversationListL(list)
                        },
                    },
                ],
                { cancelable: false }
            );
        };

        const goChat = function (item: any) {
            if (item.conversationType !== 99) {
                console.log('goChatgoChat', item);
                updateCurrentConversation({ ...item });
                // console.log('item', item);
                router.push(`/chat/${item?.groupID || item?.conversationID}`)
            } else {
                router.push("/notification")
            };

        };

        // console.log('Swipeable', item);


        return (
            <Swipeable
                ref={(ref) => (swipeableRefs.current[item.conversationID] = ref)}
                renderRightActions={() => renderRightActions(item.conversationID)}
                onSwipeableWillOpen={() => {
                    // 关闭其他打开的项
                    if (openItemId && openItemId !== item.conversationID) {
                        swipeableRefs.current[openItemId]?.close();
                    }
                    setOpenItemId(item.conversationID); // 设置当前打开的项 ID
                }}
                onSwipeableWillClose={() => {
                    setOpenItemId(null); // 清空当前打开的项 ID
                }}
                overshootFriction={1} // 关闭时增加摩擦力以加快动画速度
            >
                <TouchableOpacity style={styles.chatItem} onPress={() => goChat(item)}>
                    <Image source={{ uri: item?.faceURL || "https://hd-uat-1258162617.cos.ap-guangzhou.myqcloud.com/icon/default_profile.png" }} style={styles.avatar} />
                    {/*{*/}
                    {/*    item.conversationType == 1 || item.conversationType == 3 && (*/}
                    {/*        <Image source={{ uri: item?.faceURL }} style={styles.avatar} />*/}
                    {/*    )*/}
                    {/*}*/}
                    {/*{*/}
                    {/*    item.conversationType == 3 && (*/}
                    {/*        <GroupAvatar avatars={avatars} centerAvatar={centerAvatar}/>*/}
                    {/*    )*/}
                    {/*}*/}
                    <View style={styles.textContainer}>
                        <View style={[styles.bodyContent]}>
                            <View style={styles.chatName}>
                                <Text style={styles.chatNameText}>{item.showName || ""}</Text>
                            </View>
                            <Text style={styles.chatTimeText}>{ formatConversionTime(item.latestMsgSendTime) }</Text>
                        </View>
                        <View style={styles.bodyFooter}>

                            {
                                item.conversationType == 99 && (
                                    <View style={[styles.message, { flexDirection: "row" }]}>
                                        <Text style={styles.messageText}>

                                        </Text>
                                    </View>
                                )
                            }

                            {
                                JSON.parse(item.latestMsg).contentType === 1201 && (
                                    <View style={[styles.message, { flexDirection: "row" }]}>
                                       <Text style={styles.messageText}>
                                           你们已经成为好友，可以开始聊天了！
                                       </Text>
                                    </View>
                                )
                            }

                            {
                                JSON.parse(item.latestMsg).contentType === 1501 && (
                                    <View style={[styles.message, { flexDirection: "row" }]}>
                                        <Text style={styles.messageText}>{ JSON.parse(JSON.parse(item.latestMsg).notificationElem.detail).opUser.nickname }创建了群聊</Text>
                                    </View>
                                )
                            }

                            {
                                JSON.parse(item.latestMsg).contentType === 1504 && (
                                    <View style={[styles.message, { flexDirection: "row" }]}>
                                        <Text style={styles.messageText}>{ JSON.parse(JSON.parse(item.latestMsg).notificationElem.detail).quitUser.nickname }退出了群聊</Text>
                                    </View>
                                )
                            }

                            {
                                JSON.parse(item.latestMsg).contentType === 1509 && (
                                    <View style={[styles.message, { flexDirection: "row" }]}>
                                        <Text style={styles.messageText}>{ JSON.parse(JSON.parse(item.latestMsg).notificationElem.detail).opUser.nickname }邀请了
                                            {
                                                JSON.parse(JSON.parse(item.latestMsg).notificationElem.detail).invitedUserList.map((item, index) => {
                                                    return item.nickname + "、";
                                                })
                                            }
                                            进入群聊
                                        </Text>
                                    </View>
                                )
                            }

                            {
                                JSON.parse(item.latestMsg).contentType === 1508 && (
                                    <View style={[styles.message, { flexDirection: "row" }]}>
                                        <Text style={styles.messageText}>
                                            {
                                                JSON.parse(JSON.parse(item.latestMsg).notificationElem.detail).kickedUserList.map((item, index) => {
                                                    return item.nickname + "、";
                                                })
                                            }

                                            被{ JSON.parse(JSON.parse(item.latestMsg).notificationElem.detail).opUser.nickname }踢出群聊
                                        </Text>
                                    </View>
                                )
                            }


                            {
                                JSON.parse(item.latestMsg).contentType === 1511 && (
                                    <View style={[styles.message, { flexDirection: "row" }]}>
                                        <Text style={styles.messageText}>{ JSON.parse(JSON.parse(item.latestMsg).notificationElem.detail).opUser.nickname }解散了群聊</Text>
                                    </View>
                                )
                            }

                            {
                                JSON.parse(item.latestMsg).contentType == 101 && (
                                    <View style={styles.message}>
                                        <Text style={styles.messageText}>{ formattedMessage() }</Text>
                                    </View>
                                )
                            }

                            {
                                JSON.parse(item.latestMsg).contentType == 102  && (
                                    <View style={styles.message}>
                                        <Text style={styles.messageText}> { JSON.parse(item.latestMsg).senderNickname + ":" }  [图片] </Text>
                                    </View>
                                )
                            }

                            {
                                JSON.parse(item.latestMsg).contentType == 1519  && (
                                    <View style={[styles.message, { flexDirection: "row" }]}>
                                        <Text style={{ color: item?.unreadCount > 0 ? "red" : "#9C9EAC", fontSize: 12, }}>
                                            [群公告]
                                        </Text>
                                        <Text> </Text>
                                        <Text
                                            style={[styles.messageText, { width: scaleSize(260) }]}
                                            numberOfLines={1}
                                            ellipsizeMode="tail"
                                        >{ JSON.parse(JSON.parse(item.latestMsg).notificationElem.detail).opUser.nickname + ":" + JSON.parse(JSON.parse(item.latestMsg).notificationElem.detail).group.notification  }
                                        </Text>
                                    </View>
                                )
                            }
                            {
                                item.unreadCount > 0 && (
                                    <View style={styles.unRead}>
                                        <Text style={styles.unReadText}>{ item.unreadCount || "" }</Text>
                                    </View>
                                )
                            }
                        </View>
                    </View>
                </TouchableOpacity>
            </Swipeable>
        )
    };

    return (
        <View style={styles.container}>
            <View style={[styles.newTitle, { paddingTop: insets.top }]}>
                <Text style={styles.newTitleText}>消息</Text>
            </View>
            {/*<View style={styles.body}>*/}
            {/*    <GestureHandlerRootView style={{ flex: 1 }}>*/}
            {/*        <FlatList*/}
            {/*            data={conversationList}*/}
            {/*            renderItem={newRenderComponent}*/}
            {/*            keyExtractor={(item) => item.conversationID}*/}
            {/*        >*/}
            {/*        </FlatList>*/}
            {/*    </GestureHandlerRootView>*/}
            {/*</View>*/}
            {
                isLogin && (
                    <View style={styles.body}>
                        <GestureHandlerRootView style={{ flex: 1 }}>
                            <FlatList
                                data={conversationList}
                                renderItem={newRenderComponent}
                                keyExtractor={(item) => item.conversationID}
                            >
                            </FlatList>
                        </GestureHandlerRootView>
                    </View>
                )
            }
            {
                !isLogin && (
                    <View style={{ flex: 1 }}>
                        <Empty/>
                    </View>
                )
             }
        </View>
    );

}

const styles = StyleSheet.create({
    newTitle: {
    },
    newTitleText: {
        fontSize: 16,
        color: "#2A2B30",
        textAlign: "center",
        fontWeight: "bold"
    },
    container: {
        flex: 1,
        backgroundColor: "#FFF"
    },
    header: {
        height: 40,
        backgroundColor: '#f8f8f8',
        justifyContent: 'center',
        alignItems: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#ddd',
    },
    body: {
        backgroundColor: '#FFF',
        flex: 1,
    },
    deleteButton: {
        backgroundColor: 'red',
        justifyContent: 'center',
        alignItems: 'center',
        width: 80,
    },
    deleteButtonText: {
        color: 'white',
        fontWeight: 'bold',
    },
    chatItem: {
        flexDirection: 'row',
        paddingHorizontal: 12,
        alignItems: 'center',
    },
    avatar: {
        width: 42,
        height: 42,
        borderRadius: 25,
        marginRight: 10,
    },
    textContainer: {
        flex: 1,
        borderBottomWidth: 0.3,
        paddingVertical: 14,
        borderBottomColor: "#E4E6EC",
    },
    name: {
        fontSize: 16,
        fontWeight: 'bold',
    },
    message: {
        color: '#777',
        marginTop: 5,
        width: scaleSize(250)
    },
    separator: {
        height: 1,
        backgroundColor: '#eee',
    },
    bodyContent: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between"
    },
    bodyFooter: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between"
    },
    chatName: {},
    chatNameText: {
        fontSize: 14,
        fontWeight: "bold",
        color: "#2A2B30"
    },
    chatTime: {},
    chatTimeText: {
        color: "#9C9EAC",
        fontSize: 12,
    },
    messageText: {
        color: "#9C9EAC",
        fontSize: 12,
        flexWrap: "nowrap"
    },
    unRead: {
        height: 16,
        marginTop: 5,
        borderRadius: 50,
        paddingHorizontal: 5,
        backgroundColor: "#FB4B34",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center"
    },
    unReadText: {
        color: "#fff",
        fontSize: 12,
    },
    deleteText: {
        color: '#fff',
        fontWeight: 'bold',
    },
});
